namespace com.stifel.ProjectMgmt.Features.ProjectMgmtBldList_Feature
{
    using System;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.Linq;
    using System.Runtime.InteropServices;

    using com.stifel;
    using com.stifel.Extensions.SharePointExtensions;
    using com.stifel.SharePoint;

    using Microsoft.SharePoint;

    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>
    [Guid( "ca8a5bbc-cd76-4cb1-bdc8-7a347903f767" )]
    public class ProjectMgmtBldList_FeatureEventReceiver : SPFeatureReceiver
    {
        #region Fields

        //2c17e7d4-39ae-4f47-8e0c-3ac93d848892
        const string FEATURE = "com.stifel.ProjectMgmt-Build Project List";
        const string PROJECTS_rootFolderName = "projects";

        #endregion Fields

        #region Methods

        public override void FeatureActivated( SPFeatureReceiverProperties properties )
        {
            try
            {
                if ( !( properties.Feature.Parent is SPWeb ) )
                {
                    throw new Exception( string.Format( "{0} :: Error activating feature. Feature parent is not of type SPWeb.", FEATURE ) );
                }

                CustomLoggingService.LogMessage( CustomLoggingService.Area.FeatureInfrastructure, "{0} :: Feature activating.", FEATURE );
                createLists( properties );
                createViews( properties );
                CustomLoggingService.LogMessage( CustomLoggingService.Area.FeatureInfrastructure, "{0} :: Feature activated.", FEATURE );
            }
            catch ( Exception e )
            {
                throw new Exception( string.Format( "Error occurred in {0} FeatureActivated. {1} {2}", FEATURE, e.Message, e.StackTrace ), e );
            }
        }

        public override void FeatureDeactivating( SPFeatureReceiverProperties properties )
        {
            try
            {
                if ( !( properties.Feature.Parent is SPWeb ) )
                {
                    CustomLoggingService.LogCritical( CustomLoggingService.Area.FeatureInfrastructure, "{0} :: Error deactivating feature. Feature parent is not of type SPWeb.", FEATURE );
                    return;
                }

                CustomLoggingService.LogMessage( CustomLoggingService.Area.FeatureInfrastructure, "{0} :: Feature deactivating.", FEATURE );
                deleteLists( properties );
                CustomLoggingService.LogMessage( CustomLoggingService.Area.FeatureInfrastructure, "{0} :: Feature deactivated.", FEATURE );
            }
            catch ( Exception e )
            {
                throw new Exception( string.Format( "Error occurred in {0} FeatureDeactivating. {1} {2}", FEATURE, e.Message, e.StackTrace ), e );
            }
        }

        public override void FeatureInstalled( SPFeatureReceiverProperties properties )
        {
            try
            {
                CustomLoggingService.LogMessage( CustomLoggingService.Area.FeatureInfrastructure, "{0} :: Feature installed.", FEATURE );
            }
            catch ( Exception e )
            {
                throw new Exception( string.Format( "Error occurred in {0} FeatureInstalled function. {1} {2}", FEATURE, e.Message, e.StackTrace ), e );
            }
        }

        public override void FeatureUninstalling( SPFeatureReceiverProperties properties )
        {
            try
            {
                CustomLoggingService.LogMessage( CustomLoggingService.Area.FeatureInfrastructure, "{0} :: Feature uninstalling.", FEATURE );
            }
            catch ( Exception e )
            {
                throw new Exception( string.Format( "Error occurred in {0} FeatureUninstalling. {1} {2}", FEATURE, e.Message, e.StackTrace ), e );
            }
        }

        void createLists( SPFeatureReceiverProperties properties )
        {
            createLists_projects( properties );
        }

        void createLists_projects( SPFeatureReceiverProperties properties )
        {
            List<string> l = new string[ ]{
                "Stifel Project",
                "Stifel Task"
            }.ToList( );
            using ( SPWeb spWeb = properties.GetWeb( ) )
            {
                if ( spWeb.Lists.ContainsList( PROJECTS_rootFolderName ) )
                {
                    CustomLoggingService.LogWarning( CustomLoggingService.Area.FeatureInfrastructure, "{0} :: List {1} not created. List already exists.", FEATURE, PROJECTS_rootFolderName );
                }
                else
                {
                    // create projects list
                    string title = string.Format( "{0} Projects", spWeb.Title );
                    string description = string.Format( "This is a project tracking list for {0}. The list facilitates tracking multiple projects and the assignment of tasks to different people.", spWeb.Title );
                    SPList spList = spWeb.CreateGenericList( PROJECTS_rootFolderName, title, description, false );

                    spList.ContentTypesEnabled = true;
                    //spList.ContentTypes.Delete( spList.ContentTypes[ "Item" ].Id );

                    foreach ( SPContentType o in spList.ContentTypes )
                    {
                        o.Hidden = true;
                    }

                    foreach ( string s in l )
                    {
                        SPContentType p = spWeb.GetContentTypeByName( s );
                        if ( p != null )
                            spList.ContentTypes.Add( p );
                    }
                    spList.Update( );

                    CustomLoggingService.LogMessage( CustomLoggingService.Area.FeatureInfrastructure, "{0} :: List {1} created.", FEATURE, PROJECTS_rootFolderName );
                }
            }
        }

        void createViews( SPFeatureReceiverProperties properties )
        {
            createViews_ActiveProjects( properties );
            createViews_CompletedProjects( properties );
            createViews_InactiveProjects( properties );
        }

        void createViews_ActiveProjects( SPFeatureReceiverProperties properties )
        {
            using ( SPWeb spWeb = properties.GetWeb( ) )
            {
                SPList spList = spWeb.Lists.GetListByRootFolder( PROJECTS_rootFolderName );
                List<string> viewFields = new List<string>( );
                viewFields.Add( "LinkTitleNoMenu" );
                viewFields.Add( "sn_prjmgt_ProjectDescription" );
                string query = "<OrderBy><FieldRef Name='sn_prjmgt_TeamRanking' /><FieldRef Name='Title' /></OrderBy><Where><Or><Eq><FieldRef Name='sn_prjmgt_ProjectStatus' /><Value Type='Text'>Not Started</Value></Eq><Eq><FieldRef Name='sn_prjmgt_ProjectStatus' /><Value Type='Text'>In Progress</Value></Eq></Or></Where>";
                spList.CreateView( "activeprojects", "Active Projects", viewFields, query, 100, true, true, SPViewCollection.SPViewType.Html, true );
            }
        }

        void createViews_CompletedProjects( SPFeatureReceiverProperties properties )
        {
            using ( SPWeb spWeb = properties.GetWeb( ) )
            {
                SPList spList = spWeb.Lists.GetListByRootFolder( PROJECTS_rootFolderName );
                List<string> viewFields = new List<string>( );
                viewFields.Add( "LinkTitleNoMenu" );
                viewFields.Add( "sn_prjmgt_ProjectDescription" );
                string query = "<OrderBy><FieldRef Name='sn_prjmgt_CompletedDate' Ascending='FALSE' /><FieldRef Name='Title' /></OrderBy><Where><Eq><FieldRef Name='sn_prjmgt_ProjectStatus' /><Value Type='Text'>Completed</Value></Eq></Where>";
                spList.CreateView( "completedprojects", "Completed Projects", viewFields, query, 100, true, false, SPViewCollection.SPViewType.Html, true );
            }
        }

        void createViews_InactiveProjects( SPFeatureReceiverProperties properties )
        {
            using ( SPWeb spWeb = properties.GetWeb( ) )
            {
                SPList spList = spWeb.Lists.GetListByRootFolder( PROJECTS_rootFolderName );
                List<string> viewFields = new List<string>( );
                viewFields.Add( "LinkTitleNoMenu" );
                viewFields.Add( "sn_prjmgt_ProjectDescription" );
                string query = "<OrderBy><FieldRef Name='sn_prjmgt_DueDate' /><FieldRef Name='Title' /></OrderBy><Where><Eq><FieldRef Name='sn_prjmgt_ProjectStatus' /><Value Type='Text'>Deferred</Value></Eq></Where>";
                spList.CreateView( "inactiveprojects", "Inactive Projects", viewFields, query, 100, true, false, SPViewCollection.SPViewType.Html, true );
            }
        }

        void deleteLists( SPFeatureReceiverProperties properties )
        {
            deleteLists_projects( properties );
        }

        void deleteLists_projects( SPFeatureReceiverProperties properties )
        {
            bool ok = false;
            using ( SPWeb spWeb = properties.GetWeb( ) )
            {
                ok = spWeb.DeleteList( PROJECTS_rootFolderName, false );
            }
            if ( ok )
                CustomLoggingService.LogMessage( CustomLoggingService.Area.FeatureInfrastructure, "{0} :: List {1} removed.", FEATURE, PROJECTS_rootFolderName );
            else
                CustomLoggingService.LogMessage( CustomLoggingService.Area.FeatureInfrastructure, "{0} :: List {1} not removed.", FEATURE, PROJECTS_rootFolderName );
        }

        #endregion Methods

        #region Other

        // Uncomment the method below to handle the event raised when a feature is upgrading.
        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}

        #endregion Other
    }
}